<template>
  <div class="page-container">
    <a-tabs :active-key="activeTabsKey" @change="tabsChangeFn">
      <a-tab-pane key="store-info" title="门店信息">
        <store-info ref="storeInfoRef" :form="form" :status="status" />
      </a-tab-pane>
      <a-tab-pane key="shortSiteConfig" title="自驾短租配置" v-if="userServiceTypes.includes(1)">
        <service-config key="1" configTypePropStr="shortSiteConfig" ref="dzServiceConfigRef" :status="status" />
      </a-tab-pane>
      <a-tab-pane key="longSiteConfig" title="自驾长租配置" v-if="userServiceTypes.includes(2)">
        <service-config key="2" configTypePropStr="longSiteConfig" ref="czServiceConfigRef" :status="status" />
      </a-tab-pane>
    </a-tabs>
  </div>
  <page-form-footer :ok-loading="okLoading" @ok="submitFn" />
</template>

<script setup name="StoreManageForm">
  import { ref, provide } from 'vue'
  import { useRoute } from 'vue-router'
  import { addOreditSiteLease, getSiteLeaseDetail } from '@/api/asset/site'
  import { getEnterpriseDetail } from '@/api/asset/enterprise.js'
  import serviceConfig from './components/service-config.vue'
  import storeInfo from './components/store-info.vue'
  import { usePageDict } from '@/hooks/useDict'
  import useNavigate from '@/hooks/useNavigate'

  const { navigateBack } = useNavigate()
  import { isValid } from '@/utils'
  const route = useRoute()
  const carsiteDict = usePageDict('carsiteDict')
  // 暴露给子组件 dict 对象
  provide('dict', carsiteDict)
  const storeInfoRef = ref()
  const dzServiceConfigRef = ref()
  const czServiceConfigRef = ref()
  const activeTabsKey = ref('store-info')
  const tabsChangeFn = (key) => {
    activeTabsKey.value = key
  }
  // 状态（新增 | 编辑）
  const status = ref('add')
  // 长短租配置的默认值
  const defaultConfig = {
    isNightServiceFee: 0,
    hourAmountType: 1,
    isOnsiteService: 1,
    hourToDay: 7,
    isOnsiteServiceFee: 0,
    isOnsiteMaxRadius: 1,
    // 同城异店还车
    isDiffSiteReturn: 0,
    isDiffSiteFee: 0,
    diffSiteReturnCar: 0,
    // 跨城异店还车
    isDiffCityReturn: 0,
    isDiffCityFee: 0,
    diffCityReturnCar: 0,
    // 超时费
    isOverTimeFee: 0,
    // 超里程费
    isOverMilesFee: 0,
    // 是否启用门店取消
    isEnableSiteCancel: 0,
    // 未支付自动取消时长(分钟)
    cancelUnpaidAutoTime: 15,
    // 支付后免费取消时长(分钟)
    cancelPaidFreeTime: 30,
    // 是否支持无责取消
    cancelWeekdayBeforeRule: 0,
  }

  let form = ref({
    status: 10, // 默认启用
    contactList: [{ name: '', phone: '' }],
    shortSiteConfig: { ...defaultConfig, configType: 1 },
    longSiteConfig: { ...defaultConfig, configType: 0 },
    carHousekeepList: [{ staffId: undefined }],
    fromTime: '00:00',
    toTime: '00:00',
  })
  // 暴露给子组件 form 对象
  provide('form', form)
  const routePrams = route.params
  if (routePrams.id) {
    status.value = 'edit'
    // 获取门店详情
    getSiteLeaseDetail({ id: routePrams.id }).then((res) => {
      if (res.code == 200) {
        const result = res.result
        result.status = parseInt(result.status)
        let contactList = result.contactList
        if (!contactList || (contactList && contactList.length == 0)) {
          // 默认一条数据
          result.contactList = [{}]
        }
        // 门店坐标
        result.lnglat = `${result.longitudeGd},${result.latitudeGd}`

        // 长短租配置
        handleDefaultConfig(result, 'shortSiteConfig')
        handleDefaultConfig(result, 'longSiteConfig')
        result.carHousekeepList = JSON.parse(JSON.stringify(result.carHouseKeepIdList)) || []
        result.carHousekeepList.forEach((item) => {
          item.staffName = item.realname
          item.staffPhone = item.phone
          item.staffId = item.id
          item.staffStatusName = item.staffStatusName || undefined
        })
        while (result.carHousekeepList.length < 1) {
          result.carHousekeepList.push({ staffId: undefined })
        }
        form.value = result
      }
    })
  }
  // 处理长短租配置默认值
  const handleDefaultConfig = (result, configProp) => {
    let config = result[configProp]
    if (!config) {
      result[configProp] = {
        ...defaultConfig,
        configType: configProp == 'shortSiteConfig' ? 1 : 0,
      }
    } else {
      // 存在配置，但是部分配置可能为空，此时补充一些默认值
      for (var k in defaultConfig) {
        if (config[k] === null) {
          config[k] = defaultConfig[k]
        }
      }
    }
  }

  // 企业信息
  let userServiceTypes = ref([])
  getEnterpriseDetail().then((res) => {
    if (res.code == 200) {
      const result = res.result
      userServiceTypes.value = result.userServiceTypes
    }
  })

  const okLoading = ref(false)
  const submitFn = (noticeSuccess) => {
    let dzRef = dzServiceConfigRef.value
    let czRef = czServiceConfigRef.value
    const promiseList = [storeInfoRef.value.validateFn()]
    let fmValue = form.value
    let fmSatus = fmValue.status
    // 10 启用 20 停用
    // 启用需检验是否必填项都填写
    if (fmSatus == 10) {
      if (dzRef) promiseList.push(dzRef.validateFn())
      if (czRef) promiseList.push(czRef.validateFn())
    }
    Promise.all(promiseList)
      .then(() => {
        console.log('验证通过')
        console.log(form.value)
        let siteConfigList = undefined
        if (dzRef || czRef) {
          siteConfigList = []
          if (dzRef) {
            siteConfigList.push({
              configType: 1,
              ...form.value.shortSiteConfig,
            })
          }
          if (czRef) {
            siteConfigList.push({
              configType: 0,
              ...form.value.longSiteConfig,
            })
          }
        }

        let param = {
          ...form.value,
          siteConfigList: siteConfigList,
          shortSiteConfig: undefined,
          longSiteConfig: undefined,
        }
        // 处理联系人信息
        let contactList = param.contactList
        if (contactList && contactList.length > 0) {
          contactList = JSON.parse(JSON.stringify(contactList))
          for (let i = 0; i < contactList.length; i++) {
            let item = contactList[i]
            if (!isValid(item.name) && !isValid(item.phone)) {
              contactList.splice(i, 1)
              i--
            }
          }
          param.contactList = contactList
        }
        // 处理零散小时配置
        let configList = param.siteConfigList
        if (configList) {
          configList.forEach((item) => {
            if (!item.hourToDay) {
              item.hourToDay = 24
            }
          })
        }
        okLoading.value = true
        addOreditSiteLease(param)
          .then(() => {
            noticeSuccess(status.value == 'add' ? '门店创建成功' : '门店编辑成功')
            navigateBack()
          })
          .finally(() => {
            okLoading.value = false
          })
      })
      .catch(({ errorKey, scrollErrorFn }) => {
        activeTabsKey.value = errorKey
        scrollErrorFn && scrollErrorFn()
      })
  }
</script>

<style lang="less" scoped></style>
